package com.example.smartagrisys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.smartagrisys.constant.OrderStatus;
import com.example.smartagrisys.constant.OrderType;
import com.example.smartagrisys.entity.Order;
import com.example.smartagrisys.entity.Product;
import com.example.smartagrisys.entity.User;
import com.example.smartagrisys.entity.SellerProduct;
import com.example.smartagrisys.mapper.OrderMapper;
import com.example.smartagrisys.service.NotificationService;
import com.example.smartagrisys.service.OrderService;
import com.example.smartagrisys.service.ProductService;
import com.example.smartagrisys.service.UserService;
import com.example.smartagrisys.service.SellerProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 订单服务实现类
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private ProductService productService;

    @Autowired
    private UserService userService;

    @Autowired
    private NotificationService notificationService;

    @Autowired
    private SellerProductService sellerProductService;

    @Override
    public Page<Order> getOrderPage(Page<Order> page, Order order) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        
        // 构建查询条件
        if (order != null) {
            // 按订单编号查询
            if (StringUtils.hasText(order.getOrderNo())) {
                wrapper.eq(Order::getOrderNo, order.getOrderNo());
            }
            
            // 按买家ID查询
            if (order.getBuyerId() != null) {
                wrapper.eq(Order::getBuyerId, order.getBuyerId());
            }
            
            // 按卖家ID查询
            if (order.getSellerId() != null) {
                wrapper.eq(Order::getSellerId, order.getSellerId());
            }
            
            // 按产品ID查询
            if (order.getProductId() != null) {
                wrapper.eq(Order::getProductId, order.getProductId());
            }
            
            // 按状态查询
            if (order.getStatus() != null) {
                wrapper.eq(Order::getStatus, order.getStatus());
            }
        }
        
        // 默认按创建时间降序排序
        wrapper.orderByDesc(Order::getCreateTime);
        
        return page(page, wrapper);
    }

    @Override
    public List<Order> getOrdersByBuyerId(Long buyerId) {
        if (buyerId == null) {
            return null;
        }
        
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getBuyerId, buyerId);
        wrapper.orderByDesc(Order::getCreateTime);
        
        return list(wrapper);
    }

    @Override
    public List<Order> getOrdersBySellerId(Long sellerId) {
        if (sellerId == null) {
            return null;
        }
        
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getSellerId, sellerId);
        wrapper.orderByDesc(Order::getCreateTime);
        
        return list(wrapper);
    }

    @Override
    public Order getOrderById(Long id) {
        if (id == null) {
            return null;
        }
        
        return getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createOrder(Order order) {
        if (order == null || order.getProductId() == null || order.getQuantity() == null) {
            log.error("订单数据不完整");
            return false;
        }
        
        // 根据订单类型判断是肥料订单还是农产品订单
        if (order.getOrderType() == OrderType.FERTILIZER) {
            // 肥料订单 - 查询卖家肥料商品
            SellerProduct sellerProduct = sellerProductService.getById(order.getProductId());
            if (sellerProduct == null) {
                log.error("肥料商品不存在，ID: {}", order.getProductId());
                return false;
            }
            
            // 验证卖家ID是否匹配
            if (!sellerProduct.getSellerId().equals(order.getSellerId())) {
                log.error("肥料商品卖家不匹配，商品卖家ID: {}, 订单卖家ID: {}", 
                        sellerProduct.getSellerId(), order.getSellerId());
                return false;
            }
            
            // 检查库存是否足够
            if (sellerProduct.getStock() < order.getQuantity().intValue()) {
                log.error("肥料库存不足，当前库存: {}，需要: {}", sellerProduct.getStock(), order.getQuantity());
                return false;
            }
            
            // 设置订单信息
            order.setOrderNo(generateOrderNo());
            order.setProductName(sellerProduct.getName());
            order.setProductImage(sellerProduct.getImage());
            order.setPrice(sellerProduct.getPrice());
            order.setTotalAmount(sellerProduct.getPrice().multiply(order.getQuantity()));
            order.setStatus(OrderStatus.PENDING); // 待付款
            order.setOrderType(OrderType.FERTILIZER); // 确保是肥料订单
            order.setOrderTime(LocalDateTime.now());
            order.setCreateTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            
            // 保存订单
            boolean result = save(order);
            
            if (result) {
                log.info("肥料订单创建成功，开始减少库存");
                // 减少肥料库存
                int newStock = sellerProduct.getStock() - order.getQuantity().intValue();
                sellerProduct.setStock(newStock);
                boolean stockResult = sellerProductService.updateById(sellerProduct);
                if (!stockResult) {
                    log.error("肥料库存更新失败");
                    throw new RuntimeException("肥料库存更新失败");
                }
                log.info("肥料库存更新成功，当前库存: {}", sellerProduct.getStock());
                
                // 确保order对象包含生成的ID
                LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Order::getOrderNo, order.getOrderNo());
                Order savedOrder = getOne(queryWrapper);
                if (savedOrder != null) {
                    order.setId(savedOrder.getId());
                    log.info("肥料订单已保存，ID: {}, 订单号: {}", order.getId(), order.getOrderNo());
                }
            }
            
            return result;
        } else {
            // 农产品订单 - 查询农产品信息
            Product product = productService.getById(order.getProductId());
            if (product == null) {
                log.error("农产品不存在，ID: {}", order.getProductId());
                return false;
            }
            
            // 验证卖家ID是否匹配
            if (!product.getFarmerId().equals(order.getSellerId())) {
                log.error("农产品卖家不匹配，商品卖家ID: {}, 订单卖家ID: {}", 
                        product.getFarmerId(), order.getSellerId());
                return false;
            }
            
            // 检查库存是否足够
            if (product.getStock().compareTo(order.getQuantity()) < 0) {
                log.error("农产品库存不足，当前库存: {}，需要: {}", product.getStock(), order.getQuantity());
                return false;
            }
            
            // 设置订单信息
            order.setOrderNo(generateOrderNo());
            order.setProductName(product.getName());
            order.setProductImage(product.getImage());
            order.setPrice(product.getPrice());
            order.setTotalAmount(product.getPrice().multiply(order.getQuantity()));
            order.setStatus(OrderStatus.PENDING); // 待付款
            order.setOrderType(OrderType.PRODUCT); // 确保是农产品订单
            order.setOrderTime(LocalDateTime.now());
            order.setCreateTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            
            // 保存订单
            boolean result = save(order);
            
            if (result) {
                // 减少库存
                product.setStock(product.getStock().subtract(order.getQuantity()));
                boolean stockResult = productService.updateById(product);
                if (!stockResult) {
                    log.error("农产品库存更新失败");
                    throw new RuntimeException("农产品库存更新失败");
                }
                log.info("农产品库存更新成功，当前库存: {}", product.getStock());
                
                // 确保order对象包含生成的ID
                LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Order::getOrderNo, order.getOrderNo());
                Order savedOrder = getOne(queryWrapper);
                if (savedOrder != null) {
                    order.setId(savedOrder.getId());
                    log.info("农产品订单已保存，ID: {}, 订单号: {}", order.getId(), order.getOrderNo());
                }
            }
            
            return result;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean payOrder(Long id) {
        if (id == null) {
            return false;
        }
        
        // 查询订单
        Order order = getById(id);
        if (order == null || order.getStatus() != OrderStatus.PENDING) {
            log.error("支付失败：订单不存在或状态不是待付款，订单ID: {}, 当前状态: {}", id, order != null ? order.getStatus() : "null");
            return false;
        }
        
        // 更新订单状态
        order.setStatus(OrderStatus.PAID); // 待发货
        order.setPayTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        return updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean shipOrder(Long id) {
        if (id == null) {
            log.error("发货失败：订单ID为空");
            return false;
        }
        
        // 查询订单
        Order order = getById(id);
        if (order == null) {
            log.error("发货失败：订单不存在，ID: {}", id);
            return false;
        }
        
        if (order.getStatus() != OrderStatus.PAID) {
            log.error("发货失败：订单状态不是待发货，当前状态: {}, 订单ID: {}", order.getStatus(), id);
            return false;
        }
        
        log.info("开始发货处理，订单ID: {}, 订单号: {}, 当前状态: {}", id, order.getOrderNo(), order.getStatus());
        
        // 更新订单状态
        order.setStatus(OrderStatus.SHIPPED); // 待收货
        order.setShipTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        boolean result = updateById(order);
        
        if (result) {
            log.info("订单发货成功，订单ID: {}, 订单号: {}, 新状态: {}", id, order.getOrderNo(), order.getStatus());
        } else {
            log.error("订单发货失败，订单ID: {}, 订单号: {}", id, order.getOrderNo());
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean receiveOrder(Long id) {
        if (id == null) {
            return false;
        }
        
        // 查询订单
        Order order = getById(id);
        if (order == null || order.getStatus() != OrderStatus.SHIPPED) {
            return false;
        }
        
        // 更新订单状态
        order.setStatus(OrderStatus.COMPLETED); // 已完成
        order.setCompleteTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        return updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(Long id) {
        if (id == null) {
            return false;
        }
        
        // 查询订单
        Order order = getById(id);
        if (order == null || order.getStatus() >= OrderStatus.COMPLETED) {
            return false;
        }
        
        // 修改：允许待支付(status=0)和已支付未发货(status=1)的订单取消
        // 不允许已发货(status=2)及以上状态的订单取消
        if (order.getStatus() > OrderStatus.PAID) {
            return false;
        }
        
        // 记录原状态，用于后续逻辑判断
        int originalStatus = order.getStatus();
        
        // 更新订单状态
        order.setStatus(OrderStatus.CANCELLED); // 已取消
        order.setUpdateTime(LocalDateTime.now());
        
        boolean result = updateById(order);
        
        if (result) {
            // 恢复库存
            Product product = productService.getById(order.getProductId());
            if (product != null) {
                product.setStock(product.getStock().add(order.getQuantity()));
                productService.updateById(product);
            }
            
            // 如果是已支付订单，需要处理退款逻辑
            if (originalStatus == OrderStatus.PAID) {
                // TODO: 实际项目中，这里应该调用支付系统的退款API
                log.info("订单{}已取消，需要退款处理，金额: {}", order.getOrderNo(), order.getTotalAmount());
                
                // 创建买家退款通知
                try {
                    String title = "订单已取消，退款处理中";
                    String content = "您的订单 " + order.getOrderNo() + " 已成功取消，退款将在1-3个工作日内退回您的支付账户，请留意。";
                    
                    notificationService.createSystemNotification(
                        order.getBuyerId(),   // 发送给买家
                        title,
                        content,
                        "order"               // 类型为订单
                    );
                    
                    log.info("为买家(ID:{})创建订单取消通知", order.getBuyerId());
                } catch (Exception e) {
                    log.error("创建买家退款通知失败", e);
                    // 不影响主流程
                }
            } else {
                // 未支付订单取消通知
                try {
                    String title = "订单已取消";
                    String content = "您的订单 " + order.getOrderNo() + " 已成功取消。";
                    
                    notificationService.createSystemNotification(
                        order.getBuyerId(),   // 发送给买家
                        title,
                        content,
                        "order"               // 类型为订单
                    );
                    
                    log.info("为买家(ID:{})创建订单取消通知", order.getBuyerId());
                } catch (Exception e) {
                    log.error("创建买家订单取消通知失败", e);
                    // 不影响主流程
                }
            }
            
            // 创建卖家通知
            try {
                // 获取买家信息
                User buyer = userService.getById(order.getBuyerId());
                String buyerName = (buyer != null) ? buyer.getUsername() : "用户" + order.getBuyerId();
                
                // 不同状态的订单，通知内容不同
                String title = "订单已取消";
                String content;
                if (originalStatus == OrderStatus.PAID) {
                    content = buyerName + "已取消已支付订单 " + order.getOrderNo() + "，请注意查看，系统将自动处理退款。";
                } else {
                    content = buyerName + "已取消待支付订单 " + order.getOrderNo() + "。";
                }
                
                notificationService.createActionNotification(
                    order.getSellerId(),          // 发送给卖家
                    title,                        // 标题
                    content,                      // 内容
                    "order",                      // 类型为订单
                    "/main/seller/seller-orders", // 跳转到卖家订单管理页
                    "查看订单",                    // 操作按钮文本
                    "warning"                     // 操作按钮类型为警告样式
                );
                
                log.info("为卖家(ID:{})创建订单取消通知", order.getSellerId());
            } catch (Exception e) {
                log.error("创建卖家订单取消通知失败", e);
                // 不影响主流程
            }
        }
        
        return result;
    }
    
    /**
     * 生成订单编号
     *
     * @return 订单编号
     */
    private String generateOrderNo() {
        // 生成格式：年月日时分秒+6位随机数
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        return timestamp + random;
    }

    @Override
    public List<Order> getAllFarmerOrders(Long farmerId) {
        if (farmerId == null) {
            return new ArrayList<>();
        }
        
        log.info("获取农户所有订单，农户ID: {}", farmerId);
        
        // 查询农户作为买家的肥料订单
        LambdaQueryWrapper<Order> buyerQuery = new LambdaQueryWrapper<>();
        buyerQuery.eq(Order::getBuyerId, farmerId)
                  .eq(Order::getOrderType, OrderType.FERTILIZER)
                  .orderByDesc(Order::getCreateTime);
        List<Order> fertilizerOrders = list(buyerQuery);
        log.info("获取到农户作为买家的肥料订单数量: {}", fertilizerOrders.size());
        
        // 查询农户作为卖家的农产品订单
        LambdaQueryWrapper<Order> sellerQuery = new LambdaQueryWrapper<>();
        sellerQuery.eq(Order::getSellerId, farmerId)
                   .eq(Order::getOrderType, OrderType.PRODUCT)
                   .orderByDesc(Order::getCreateTime);
        List<Order> productOrders = list(sellerQuery);
        log.info("获取到农户作为卖家的农产品订单数量: {}", productOrders.size());
        
        // 合并两种订单
        List<Order> allOrders = new ArrayList<>();
        allOrders.addAll(fertilizerOrders);
        allOrders.addAll(productOrders);
        
        // 按创建时间降序排序
        allOrders.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));
        
        return allOrders;
    }
} 